package com.svn.util;

import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.event.UndoableEditListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;

public class MenuStatus {

    public static boolean isCanPaste() {
	try {
	    String data = (String) Toolkit.getDefaultToolkit()
		    .getSystemClipboard().getData(DataFlavor.stringFlavor);
	    if (data != null && !"".equals(data))
		return true;
	} catch (HeadlessException e) {
	    e.printStackTrace();
	} catch (UnsupportedFlavorException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return false;
    }

    public static boolean isCanCopyOrCut(JTextComponent text) {
	return text.getSelectionStart() != text.getSelectionEnd();
    }

    public static boolean isCanRedo(JTextComponent text) {
	AbstractDocument document = (AbstractDocument) text.getDocument();
	UndoableEditListener[] undoableEditListeners = document
		.getUndoableEditListeners();
	if (undoableEditListeners.length > 0) {
	    UndoManager undo = (UndoManager) undoableEditListeners[0];
	    return undo.canRedo();
	}
	return false;
    }

    public static boolean isCanUndo(JTextComponent text) {
	AbstractDocument document = (AbstractDocument) text.getDocument();
	UndoableEditListener[] undoableEditListeners = document
		.getUndoableEditListeners();
	if (undoableEditListeners.length > 0) {
	    UndoManager undo = (UndoManager) undoableEditListeners[0];
	    return undo.canUndo();
	}
	return false;
    }

}
